package com.aizuda.easyManagerTool.config;

import cn.hutool.core.util.StrUtil;
import com.aizuda.easy.security.code.BasicCode;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.exp.impl.BasicException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
@Slf4j
@RestControllerAdvice
@RestController
public class GlobalExceptionConfig {

    /**
     * 处理Exception异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Rep handleAllExceptions(Exception e, WebRequest request) {
        if (e instanceof NoHandlerFoundException) {
            return Rep.error(BasicCode.BASIC_CODE_404);
        }
        if(e instanceof BasicException){
            BasicException cause = (BasicException) e;
            return Rep.error(cause.getCode(),cause.getMsg());
        }
        if(e.getCause() instanceof BasicException){
            BasicException cause = (BasicException) e.getCause();
            return Rep.error(cause.getCode(),cause.getMsg());
        }
        if(e instanceof IllegalArgumentException){
            return Rep.error(BasicCode.BASIC_CODE_99999.getCode(),e.getMessage());
        }
        if(e instanceof MissingServletRequestParameterException){
            log.error(e.getMessage());
            return Rep.error(BasicCode.BASIC_CODE_99998.getCode(),BasicCode.BASIC_CODE_99998.getMsg());
        }
        if(e instanceof HttpRequestMethodNotSupportedException){
            String msg = e.getMessage();
            msg = BasicCode.BASIC_CODE_99997.getMsg() +
                    (StrUtil.isEmpty(msg) ? "": msg.substring(msg.indexOf("'")-1, msg.lastIndexOf("'")+1));
            return Rep.error(BasicCode.BASIC_CODE_99997.getCode(),msg);
        }
        e.printStackTrace();
        String msg = StrUtil.isBlank(e.getMessage()) ? BasicCode.BASIC_CODE_500.getMsg() : e.getMessage();
        return Rep.error(BasicCode.BASIC_CODE_500.getCode(), msg);
    }

    @RequestMapping("/failure/authenticationFilter")
    public Rep error(@RequestParam("code") Integer code, @RequestParam("msg") String msg) {
        return Rep.error(code, msg);
    }

}
